﻿using MongoDB.Driver;
using MongoDB.Driver.Linq;
using Sustainalytics.ClientDW.Entities;
using Sustainalytics.Entities.ConnectionStrings;
using Sustainalytics.MongoDB.Extensions;
using System.Linq;

namespace Sustainalytics.DataLayer.ConnectionStrings
{
    public class ConnectionStringsRepository : IConnectionStringsRepository
    {
        private readonly string _connectionString;

       
        public ConnectionStringsRepository(string storageConnectionString = null)
        {
            _connectionString = storageConnectionString ?? MongoFactory.GetConnectionStringFromConfig("ClientPlatform");
        }

        public static IConnectionStringsRepository GetInstance(string storageConnectionString = null)
        {
            return new ConnectionStringsRepository(storageConnectionString);
        }

        public SyncLog GetLastSuccesfullSyncSession()
        {
            var connectionString = _connectionString.Replace("ClientPlatform", "ClientDWMaster");
            var collection = MongoFactory.GetCollectionFromDatabase<SyncLog>(connectionString);
            return collection.AsQueryable()
                .Where(s => s.Status == LastSessionStatus.Finished && s.TimeEnd != null)
                .OrderByDescending(s => s.TimeEnd)
                .FirstOrDefault();
        }

        public string GetCurrentDatabaseGroup() => MongoFactory.GetConnectionStrings(_connectionString).DatabaseGroup;

        public string GetConnectionString(ConnectionStringType connectionStringType)
        {
            var connectionStrings = MongoFactory.GetConnectionStrings(_connectionString);
            var properties = connectionStrings.GetType().GetProperties();
            return properties.Where(p => p.Name == connectionStringType.ToString())
                .Select(p => p.GetValue(connectionStrings, null).ToString())
                .SingleOrDefault();
        }
    }
}
